import React, { useState, useEffect } from 'react';
import { FullScreen, useFullScreenHandle } from 'react-full-screen';

interface FullscreenProps {
    children: React.ReactNode;
    className?: string;
    style?: React.CSSProperties;
    onFullscreenChange?: (isFullscreen: boolean) => void;
    disabled?: boolean;
    closeOnEscape?: boolean;
    title?: string;
}

/**
 * 全屏组件
 * 使用 react-full-screen 库实现
 * 支持通过按钮切换全屏状态，监听全屏变化事件
 */
const Fullscreen: React.FC<FullscreenProps> = ({
    children,
    className = '',
    style = {},
    onFullscreenChange,
    disabled = false,
    closeOnEscape = true,
    title = '全屏内容',
}) => {
    const handle = useFullScreenHandle();
    const [isFullscreen, setIsFullscreen] = useState(handle.active);
    const [showToggle, setShowToggle] = useState<boolean>(false);
    
    // 监听全屏状态变化
    useEffect(() => {
        setIsFullscreen(handle.active);
        if (onFullscreenChange) {
            onFullscreenChange(handle.active);
        }
    }, [handle.active, onFullscreenChange]);

    // 处理 ESC 键退出全屏
    useEffect(() => {
        if (!closeOnEscape) return;

        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === 'Escape' && isFullscreen) {
                handle.exit();
            }
        };

        document.addEventListener('keydown', handleKeyDown);
        return () => document.removeEventListener('keydown', handleKeyDown);
    }, [isFullscreen, closeOnEscape, handle]);

    // 切换全屏状态
    const toggleFullscreen = () => {
        if (disabled) return;

        if (isFullscreen) {
            handle.exit();
        } else {
            handle.enter();
        }
    };

    return (
        <div className={`fullscreen-wrapper ${className}`} style={style}
            onMouseEnter={() => setShowToggle(true)}
            onMouseLeave={() => setShowToggle(false)}
            >
            <FullScreen handle={handle} className={`${className}`}>
                <div className="fullscreen-content bh-100 position-relative">
                    {children}
                    {showToggle && !isFullscreen&& <img src="/pic/pic_full_screen.png" alt="" 
                    onClick={toggleFullscreen} 
                    className='w-15 h-15 cursor-pointer z-index-110 position-absolute top-0 right-0' />}
                    {/* 全屏状态下显示的控制栏 */}
                    {/* {isFullscreen && <div className='w-500 h-500 z-index-100 pos-a t-50'
                    style={{right:'50%',transform:'translateX(-50%)'}}
                    onMouseEnter={() => setShowBack(true)}
                    onMouseLeave={() => setShowBack(false)}>
                        { showBack && (
                            <img src="/pic/pic_open.png" alt="" onClick={toggleFullscreen} className='w-50 h-50 z-index-100 cursor-pointer pos-a t-0 r-200' />
                        )}
                    </div>} */}

                </div>
            </FullScreen>


        </div>
    );
};

export default Fullscreen;